#coding=utf-8

import queue
from tkinter import *
import tkinter as tk
from TabBase import *
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import random
import sys
import platform
import getpass
if platform.system() == "Windows":
	doc_path = ''
else:
	doc_path = u"/Users/{}/Documents".format(getpass.getuser())
	try:
		os.path.join(doc_path, u'陈意涵')
		os.mkdir(doc_path+u'/陈意涵')
	except Exception as e:
		pass
	doc_path = doc_path+u'/陈意涵/'


def pc_url(url):
	if "http://m.v.qq.com/x/bar/post/detail_h5.html" in url:
		url = url.split("=")[1]
		url = url.split("&")[0]
		url = "https://v.qq.com/doki/doki_note/detail?starid=1661556&noteid=" + url + "&dataKey=starid%3D1661556%26ftid%3D51661556%26targetid%3D2657077965"
	return url


class TabTalk(TabBase):
	"""docstring for TabTalk"""
	def __init__(self, view):
		self.less_talk_count_var = StringVar()
		self.status = "_评论"
		self.urls_list_var = StringVar()
		self.valid_urls_var = StringVar()
		self.file_path_var = StringVar()
		self.less_url_count_var = StringVar()
		super(TabTalk, self).__init__(view)
		self.all_total_var.set("总评论：0")
		self.now_total_var.set("当前评论：0")
		self.valid_urls_var.set("未导入文件")
		self.file_path_var.set("评论链接：")


	def setupUI(self, view):
		super().setupUI(self.mainView)

		Label(self.leftView, text="账户信息：").grid(sticky=W)
		Listbox(self.leftView,listvariable=self.accounts_list_var,width=55,height=10).grid(row=1,sticky=W)
		Label(self.leftView, textvariable=self.file_path_var).grid(row=2, sticky=W)
		Listbox(self.leftView,listvariable=self.urls_list_var,width=55,height=9).grid(row=3)
		Label(self.leftView, text="话术文本：").grid(row=4, sticky=W)
		Listbox(self.leftView,listvariable=self.talks_var,width=55,height=9).grid(row=5,sticky=W)

		Label(view, textvariable=self.valid_urls_var).grid(row=6,column=2,columnspan=2,pady=5,padx=5)
		Button(view, text='选择评论链接', width = 15, height=1, command=self.open_urls).grid(row=2,column=3,padx=10)
		Button(view, text='选择评论话术', width = 15, height=1, command=self.open_talks).grid(row=3,column=3,padx=10)

		fieldView = Frame(view)
		fieldView.grid(row=12,column=2,columnspan=2,pady=5,padx=5)
		Label(fieldView,text='筛选评论数小于：').grid(row=0,column=0,sticky=W, pady=5)
		Entry(fieldView, width = 3,textvariable=self.less_talk_count_var).grid(row=0,column=1, pady=5)
		self.less_talk_count_var.set("80")

		fieldView1 = Frame(view)
		fieldView1.grid(row=13,column=2,columnspan=2,pady=5,padx=5)
		Label(fieldView1,text='链接小于：').grid(row=0,column=0,sticky=W, pady=5)
		Entry(fieldView1, width = 3,textvariable=self.less_url_count_var).grid(row=0,column=1, pady=5)
		Label(fieldView1,text='提示').grid(row=0,column=3,sticky=W, pady=5)
		self.less_url_count_var.set("50")



		imgInfo = PhotoImage(file = '1.gif')
		lblImage = Label(view, image = imgInfo)
		lblImage.image = imgInfo
		lblImage.grid(row=14,column=2,sticky=S,columnspan=2)


	def add_total(self):	# 总数增加，评论，发帖子
		self.all_total += 1
		self.now_total += 1
		self.all_total_var.set("总评论：{}".format(self.all_total))
		self.now_total_var.set("当前评论：{}".format(self.now_total))



	def open_urls(self):
		if self.is_stop != True:
			tkinter.messagebox.showerror("警告","脚本已经在执行，请先\"停止\"脚本在运行导入操作")
			return
		if tkinter.messagebox.askyesno("温馨提示","是否要删除之前导入的链接"):
			self.urls_list_var.set("")
			self.urls = []
		filename = tkinter.filedialog.askopenfilename(filetypes = [('TXT', 'txt')])
		if filename != '':
			urls_files = open(filename, 'r')
			self.file_path_var.set(u"评论链接：" + filename)
			urls = urls_files.readlines()
			# 去重操作
			urls = list(set(urls))
			urls_copy = urls.copy()
			for url in urls_copy:
				temp = url.strip()
				if temp == '' or 'http' not in url:
					urls.remove(url)

			for index, url in enumerate(urls):
				urls[index] = url.strip()	# 去除末尾的空格
				urls[index] = pc_url(url)	# 将m.v转化为pc版本链接


			urls = list(set(urls))
			self.urls.extend(urls)
			self.valid_urls_var.set("有效链接数：{}".format(len(self.urls)))
			self.urls_list_var.set(tuple(self.urls))


	def start(self):
		if len(self.urls) == 0:
			tkinter.messagebox.showerror("温馨提示","请选择链接文本！！！！")
			self.is_start = False
			self.is_stop = True
			return
		count = 0
		try:
			count = int(self.less_talk_count_var.get())
		except:
			count = 0
		if count <= 0:
			tkinter.messagebox.showerror("温馨提示","筛选链接评论数应大于等于1")
			return
		count = -1
		try:
			count = int(self.less_url_count_var.get())
		except:
			count = -1
		if count <= -1:
			tkinter.messagebox.showerror("温馨提示","链接提示数应大于等于0")
			return
		super().start()
		self.less_talk_count = int(self.less_talk_count_var.get())
		self.less_url_count = int(self.less_url_count_var.get())

	def work(self):

		# 评论
		urls = self.urls.copy()

		for index,url in enumerate(urls):
			self.valid_urls_var.set("有效链接数：{}".format(len(self.urls)))
			print("准备打开第{}条评论链接".format(index+1))
			if 'http' not in url: 				# 判断链接的有效性
				print("第{}条不是有效链接，删除该链接，跳过".format(index+1))
				self.urls.remove(url)
				self.valid_urls_var.set("有效链接数：{}".format(len(self.urls)))
				self.urls_list_var.set(tuple(self.urls))
				continue

			if 'id=1661556' not in url:			# 判断链接是否是意涵Doki的链接
				print("第{}条不是意涵的Doki链接，删除该链接，并提示".format(index+1))
				self.queue.put("error,,"+ url)
				self.urls.remove(url)
				self.valid_urls_var.set("有效链接数：{}".format(len(self.urls)))
				continue

			self.driver.get(url)
			print("打开第{}条评论链接成功".format(index+1))
			try:
				print("查找评论框")
				text = self.driver.find_element_by_id("comment_txt")
			except:
				print("该帖子已删除")
				self.urls.remove(url)
				self.valid_urls_var.set("有效链接数：{}".format(len(self.urls)))
				self.urls_list_var.set(tuple(self.urls))
				continue


			# 点赞
			print("判断是否点赞")
			meta = self.driver.find_element_by_class_name("article_meta").find_element_by_tag_name('a')
			flag = meta.get_attribute('data-flag')
			if flag == "1":
				print("未点赞，准备点赞")
				meta.click()
				print("点赞成功")
			else:
				print("已点赞")


			try:
				max_count = int(self.driver.find_element_by_class_name("_comment_num").text)
			except:
				max_count = 0

			try:
				text.click()
			except:
				print("点击文本框失败，跳过该条评论")
				continue
			print("填写评论文本")
			talk = random.choice(self.talks)
			time.sleep(0.2)
			text.send_keys(talk)
			time.sleep(0.2)

			try:
				print("点击提交按钮")
				self.wait.until(EC.element_to_be_clickable((By.ID, "comment_submit"))).click()
			except:
				print("点击失败，跳过该链接")
				print ("here is :"+__file__+str(sys._getframe().f_lineno))
				continue
			else:
				# 等待提交成功
				print("点击成功，等待提交成功")
				add_count = max_count
				def is_add(driver):
					max_count = int(self.driver.find_element_by_class_name("_comment_num").text)
					return add_count < max_count
				try:
					self.wait.until(is_add)
				except Exception as e:
					print("提交失败，跳过该链接")
					continue

				print("提交成功")
				success_files = open(doc_path+u'成功评论.txt', 'a+')
				success_files.write(url)
				success_files.write("\n")
				success_files.close()
				self.add_total()

				print("判断该链接的评论数（{}）时候大于设置的评论数（{}）".format(max_count,self.less_talk_count))
			if max_count > self.less_talk_count:
				print("该链接的评论数超出设置的评论，删除该链接，写入文件")
				max_files = open(doc_path+'评论数大于{}.txt'.format(self.less_talk_count), 'a+')
				self.urls.remove(url)
				self.urls_list_var.set(tuple(self.urls))
				self.valid_urls_var.set("有效链接数：{}".format(len(self.urls)))
				max_files.write(url)
				max_files.write("\n")
				max_files.close()
				print("写入成功，并删除链接")
			else:
				print("该链接的评论数未超出设置的评论，写入有效连接")
				effective_fies = open(doc_path+u'有效链接.txt', 'a+')
				effective_fies.write(url)
				effective_fies.write("\n")
				effective_fies.close()
				print("写入有效链接成功")


			if self.is_stop_or_pause():
				return True

		self.valid_urls_var.set("有效链接数：{}".format(len(self.urls)))
		print("判断当前有效链接数（{}）是否小于设置的提示有效连接数（{}）".format(len(self.urls), self.less_url_count))
		if len(self.urls) < self.less_url_count:
			print ("当前有效链接数过少，停止运行，并提示")
			self._stop()
			self.driver.delete_all_cookies()
			self.driver.get(home_url)
			self.queue.put("url_miss")
			return True
		print("当前有效链接数大于设置的有效连接数，准备进行下一步")


		return False
